import { Injectable } from '@angular/core';

import { Observable, Subject, BehaviorSubject } from 'rxjs';

/**
 * Manages the current pending http request count.
 * For display and hiding loading icon.
 */
@Injectable()
export class PendingHttpRequestService {
    private pendingRequestCount: BehaviorSubject<number> = new BehaviorSubject(0);

    constructor() { }

    get currentPendingRequestCount$(): Observable<number> {
        return this.pendingRequestCount.asObservable();
    }

    /**
     * Increases the pending http request count when request starts. This is for display loading icon.
     */
    increaseRequestCount(): void {
        this.pendingRequestCount.next(this.pendingRequestCount.value + 1);
    }

    /**
     * Decreases pending http request count when request finishes. This for hiding loading icon.
     */
    decreaseRequestCount(): void {
        if (this.pendingRequestCount.value > 0) {
            this.pendingRequestCount.next(this.pendingRequestCount.value - 1);
        }
    }
}